package com.javaee.my.business;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/input")
public class InputController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //防止乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        String text = request.getParameter("text");
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        //text存储聊天信息，并进行合法性判断
        if (text.length()!=0) {
            String say = "";
            //获取session中的昵称
            String nickname = (String)session.getAttribute("username");

            //将昵称作为链接，并传参
            say = nickname+":"+text;
            String says = "";
            //将昵称和聊天信息一起放在上下文变量
            ServletContext context = getServletContext();
            if(context.getAttribute("says")!=null){
                says = context.getAttribute("says") + dateString+ "<br>"+say + "<br>";
            }
            else{
                says = dateString+ "<br>"+ say + "<br>";
            }
            context.setAttribute("says", says);
            request.setAttribute("says", says);
        }
        //转发
      request.getRequestDispatcher("/input.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }
}

